#import <Foundation/Foundation.h>
#import <objc/runtime.h>

#import "FWDBAccess.h"


NSArray* FWDBGetRecords(NSString* sql, NSInteger sqlid, NSString* dbpath, FWApplication* application, id<FWDBAccessDelegate> delegate)
{
    sqlite3 *database = NULL;
    @try {
        if (![[NSFileManager defaultManager] isReadableFileAtPath:dbpath]) {
            NSLog(@"LI:FWTodo: Failed to find database at location %@", dbpath);
            return nil;
        }
        
        if (sqlite3_open([dbpath UTF8String], &database) != SQLITE_OK) {
            NSLog(@"LI:FWTodo: Failed to open database at location %@", dbpath);
            return nil;
        }
        
        // Setup the SQL Statement and compile it for faster access
        sqlite3_stmt *compiledStatement = NULL;
        
        @try {
            if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &compiledStatement, NULL) != SQLITE_OK) {
                NSLog(@"LI:FWTodo: Failed to prepare statement: %s in %@ at location %@", sqlite3_errmsg(database), sql, dbpath);
                return nil;
            }
            
            NSLog(@"LI:FWTodo: Executed SQL %@", sql);
            
            NSMutableArray* result = [[[NSMutableArray alloc] initWithCapacity:10] autorelease];
            
            // Loop through the results and add them to the feeds array
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                NSObject* obj = [delegate objectForSQLRecord:compiledStatement 
                                                      withId:sqlid
                                                 application:application];
                
                if (obj)
                    [result addObject:obj];
                else
                    break;
            }
            
            return result;
        }
        @catch (NSException *exception) {
            NSLog(@"LI:FWTodo: DB Read exception: %@ at location %@", exception, dbpath);
        }
        @finally {			
            if (compiledStatement != NULL)
                sqlite3_finalize(compiledStatement);
        }
    }
    @finally {
        if (database != NULL)
            sqlite3_close(database);
    }
    
    return nil;
}
